import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { BASE_URL, JWT_LS } from '../constants'
import { IProjectManager } from '../model/interfaces'

export const getTokenFromLocalStorage = () => {
    return localStorage.getItem(JWT_LS)
}

export const projectManagersApi = createApi({
    reducerPath: 'projectManagersApi',
    baseQuery: fetchBaseQuery(
        { baseUrl: `${BASE_URL}/projectManager`, headers: {Authorization: `Bearer ${getTokenFromLocalStorage()}`}  }),
    tagTypes:['projectManagers','Projects'],
    endpoints: (builder) => ({
        getProjectManagers: builder.query<IProjectManager[], void>({
            query: () => '',
            providesTags:['projectManagers']
        }),
        createProjectManager: builder.mutation<void, IProjectManager>({
            query: (projectManager: IProjectManager) =>  ({
                method: 'POST',
                url: '',
                body: projectManager
            }),
            invalidatesTags: ['projectManagers']
        }),
        updateProjectManager: builder.mutation<void, IProjectManager>({
            query: (projectManager: IProjectManager)=> ({
                method: 'PUT',
                url: `/${projectManager._id}`,
                body: projectManager
            }),
            invalidatesTags: ['projectManagers','Projects']
        }),
        deleteProjectManager: builder.mutation<void, string>({
            query: (id: string) => ({
                method: 'DELETE',
                url: `/${id}`
            }),
            invalidatesTags: ['projectManagers','Projects']
        })
    }),
})

export const {
    useGetProjectManagersQuery,
  useLazyGetProjectManagersQuery,
  useCreateProjectManagerMutation,
  useUpdateProjectManagerMutation,
  useDeleteProjectManagerMutation,
} = projectManagersApi
